import { SysAop } from '@ohos/sysaop';

const LOG_TAG = "[SysAopTag] ";

export function hookAudio() {
  // 有返回值的函数，使用addAfter时，需要在after函数中主动返回，after函数的参数为模块/类实体、返回值。
  SysAop.addAfter("@ohos.multimedia.media", "createAVRecorder", true, (instance, result) => {
    console.info(LOG_TAG + "media.createAVRecorder() monitored from sysaop after execute.");
    if (result === undefined) {
      return result;
    }

    let resultNew = {};
    Object.getOwnPropertyNames(result).forEach(function (key) {
      resultNew[key] = result[key];
    });

    // monkey patch
    resultNew["start"] = function () {
      console.info(LOG_TAG + "AVRecorder.start() is monitored from sysaop");
      return result["start"].apply(this, arguments);
    }

    // monkey patch
    resultNew["on"] = function () {
      console.info(LOG_TAG + "AVRecorder.on() is monitored from sysaop, current state: " + arguments[0]);
      return result["on"].apply(this, arguments);
    }

    return resultNew;
  });
}

export function hookPrompt() {
  SysAop.hookMethod("@ohos.promptAction", "showToast", true, (instance, oldFunc, options) => {
    oldFunc.bind(instance)(options);
    console.info("[SysAopHookTag] promptAction.showToast() monitored from sysaop.");
  });
}

export function startAop2() {
  hookAudio();
  hookPrompt();
}